import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { getshopFreightTemplateFarmet } from "../asyncGetData/shopsData"
import { showPriceInfo } from "~store/controller/jinritemaiProduct"
import { getTestApiss, loginGetJwt, checkGetPhone, saveUserPhone, cheackUserProxyApi } from "@Api/webServerApi"
import { getShopIdData, getShopUserPhone } from "@/api/shopsApi"
// import { message } from "@bytedance/mona-ui"
import FingerprintJS from '@fingerprintjs/fingerprintjs'

export interface jinritemaiShops {
    shopFreightTemplateState: any,
    shopFreightTemplateStatus: boolean,
    shopuserjwt: any,
    userShopId: String,
    addUserPhone: boolean
}

export const getshopFreightTemplateAsync = createAsyncThunk(
    "shops/setshopFreightTemplateAsync",
    async (_: any, { dispatch }) => { // arg, { dispatch, getState, extra })
        const shopFreightTemplatData: any = await getshopFreightTemplateFarmet({ page: 1, pageSize: 100 });
        _ && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)
        return shopFreightTemplatData;
    }
);

export const testWtServer = createAsyncThunk(
    "shops/testWtServer",
    async (_: any, { dispatch }) => { // arg, { dispatch, getState, extra })
        const testWtServerData: any = await getTestApiss({ page: 1, pageSize: 100, r: _ });
        _ && typeof _ === "function" && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)
        return testWtServerData;
    }
);

export const checkGetPhoneData = createAsyncThunk(
    'shops/checkGetPhoneData',
    async (_: any, { dispatch }) => {
        checkGetPhone({ shop_id: _ }).then(res => {
            if (!res?.shop_phone) {
                dispatch(getShopPhone(_))
            }
            if (!res?.user_phone) {
                dispatch(setUserPhoneModal(true))
            }
        })
    }
)

export const cheackUserProxy = createAsyncThunk(
    'shops/cheackUserProxy',
    async (_: any, { dispatch }) => {
        const fpPromise = FingerprintJS.load()
        fpPromise
            .then((fp) => fp.get())
            .then(async (result) => {
                const {
                    // fonts, 
                    languages, // 语言，主次不同
                    // audio, 
                    screenResolution, // 分辨率
                    screenFrame, // 色域
                    deviceMemory, // 设备内存 影响域名
                    ...components } =
                    result.components
                const extendedComponents: any = {
                    ...components,
                    foo: { value: 'whatever' },
                }
                const fingerprintId =
                    FingerprintJS.hashComponents(extendedComponents)
                const res = await cheackUserProxyApi({ shopId: _, uuId: fingerprintId})
                // upUserId(fingerprintId)
            })
    }
)

export const getUserShopID = createAsyncThunk(
    "shops/setUserShopID",
    async (_: any, { dispatch }) => {
        const fp = localStorage.getItem('__tea_cache_tokens_2018')
        try {
            const fpJson = JSON.parse(fp)
            const fpdata = fpJson.user_unique_id
            const shopIdData: any = await getShopIdData({ fp: fpdata, verifyFp: fpdata })
            if (!shopIdData.code) {
                dispatch(checkGetPhoneData(shopIdData.data.shopId))
                dispatch(cheackUserProxy(shopIdData.data.shopId))
                return shopIdData.data.shopId
            }
        } catch (error) {
            throw new Error('获取shopid错误!')
        }
    }
)

export const getShopPhone = createAsyncThunk(
    'shops/setShopPhone',
    async (_: any, { dispatch }) => {
        const fp = localStorage.getItem('__tea_cache_tokens_2018')
        try {
            const fpJson = JSON.parse(fp)
            const fpdata = fpJson.user_unique_id
            const getShopUserPhoneData: any = await getShopUserPhone({ fp: fpdata, verifyFp: fpdata })
            const shopPhoneData = getShopUserPhoneData.data.phones && getShopUserPhoneData.data.phones.length && getShopUserPhoneData.data.phones[0].mobile
            saveUserPhone({ shop_id: _, shop_phone: shopPhoneData }).then(res => {

            })
        } catch (error) {
            throw new Error('获取号码错误!')
        }
    }
)

export const setUserPhoneFun = createAsyncThunk(
    'shops/getUserPhoneFun',
    async (_: any, { getState, dispatch }) => {
        const { jinritemaiShops } = getState() as any;
        saveUserPhone({ shop_id: jinritemaiShops.userShopId, user_phone: _ }).then(res => {
            if (!res.code) {
               alert("保存成功")
            } else {
               alert(res.msg)
            }
            dispatch(setUserPhoneModal(false))
        })
    }
)

export const shopLogin = createAsyncThunk(
    'shops/shopLogin',
    async (_: any, { dispatch }) => {
        const fp = localStorage.getItem('__tea_cache_tokens_2018')
        try {
            if (fp) {
                const fpJson = JSON.parse(fp)
                const fpdata = fpJson.user_unique_id
                const shopIdData: any = await getShopIdData({ fp: fpdata, verifyFp: fpdata })
                const getShopUserPhoneData: any = await getShopUserPhone({ fp: fpdata, verifyFp: fpdata })
                const shopPhoneData = getShopUserPhoneData.data.phones && getShopUserPhoneData.data.phones.length && getShopUserPhoneData.data.phones[0].mobile
                if (!shopIdData.code) {
                    const getJwt = await loginGetJwt({ shop_id: shopIdData.data?.shopId, shop_phone: shopPhoneData }).catch((e) => { console.log('登录信息异常：', e) })
                    localStorage.setItem('wtshopuser', JSON.stringify(getJwt))
                    dispatch(shopuserjwtSet(getJwt))
                    _ && typeof _ === 'function' && _(getJwt)
                }
                _ && typeof _ === 'function' && _(false)
            }
        } catch (error) {
            _ && typeof _ === 'function' && _(false)
            throw new Error(error);
        }

    }
)

const jinritemaiShops = createSlice({
    name: "jinritemaiShops",
    initialState: {
        shopFreightTemplateState: [],
        shopFreightTemplateStatus: false,
        shopuserjwt: {},
        userShopId: '',
        addUserPhone: false
    },
    reducers: {
        shopuserjwtSet: (state, action) => {
            state.shopuserjwt = action.payload
        },
        setUserPhoneModal: (state, action) => {
            state.addUserPhone = action.payload
        }
    },
    extraReducers: (builder) => {
        builder.addCase(getshopFreightTemplateAsync.fulfilled, (state, action) => {
            state.shopFreightTemplateState = action.payload
            state.shopFreightTemplateStatus = true
        })
        builder.addCase(getUserShopID.fulfilled, (state, action) => {
            state.userShopId = action.payload
        })
    }
})

export const { shopuserjwtSet, setUserPhoneModal } = jinritemaiShops.actions

export default jinritemaiShops.reducer